package cn.lee.chp2;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletException;

import cn.lee.TomcatConstants;

public class ServletContainer {
    private Map servlets = new HashMap();
    
    public void init() throws ServletException{
//        PrimitiveServlet servlet = new PrimitiveServlet();
//        servlet.init(null);
        
        URLClassLoader loader = null;
        
        try {
            //create a URLClassLoader
            URL[] urls = new URL[1];
            URLStreamHandler streamHandler = null;
            File classPath = new File(TomcatConstants.CLASS_ROOT);
            //the forming of repository is taken from the
            // createClassLoader method in
            //org.apache.catalina.strtup.ClassLoaderFactory
            String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
            //the code for forming the URL is taken from
            //the addRepository method in
            //org.apache.catalina.loader.StandardClassLoader.
            urls[0] = new URL(null, repository, streamHandler);
            loader = new URLClassLoader(urls);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        Class myclass = null;
        try {
            myclass = loader.loadClass("cn.lee.chp2.PrimitiveServlet");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Servlet servlet = null;
        try {
            servlet = (Servlet) myclass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        servlet.init(null);
        
        servlets.put("/primitiveServlet", servlet);
    }
    
    public Servlet retrieveServlet(String uri){
        return (Servlet) servlets.get(uri);
    }
    
    public void destory(){
        Iterator it= servlets.values().iterator();
        while(it.hasNext()){
            Servlet servlet = (Servlet)it.next();
            servlet.destroy();
        }
    }
}
